﻿using HomagChina.Basic.CCT.Db.CCT_Db;
using HomagChina.Basic.CCT.Db.Printer_Db;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using Telerik.Windows.Data;
using Untilly;

namespace Proxy
{
    public class SearchInfoHandle
    {
        private bool result;

        private CommonHandle Handle_Common;

        public SearchInfoHandle()
        {
            Handle_Common = new CommonHandle();
        }

        /// <summary>
        /// 根据upi获取信息
        /// </summary>
        /// <param name="Reference">Reference</param>
        /// <returns></returns>
        public T_BoardInfo GetPartInfoByReference(string Reference)
        {
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    T_BoardInfo T = Db.T_BoardInfo.Where(s => s.Reference == Reference).FirstOrDefault();
                    return T ?? null;
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetPartInfoByReference:" + ex.Message);
                return null;
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public ObservableCollection<BoardInfoModel> GetTransOnLineInfo()
        {
            int i = 0;
            ObservableCollection<BoardInfoModel> List_Model = new ObservableCollection<BoardInfoModel>();
            List<View_TransOnlineRecordsDetail> List_T = new List<View_TransOnlineRecordsDetail>();
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    List_T = Db.View_TransOnlineRecordsDetail.ToList();
                    foreach (var T in List_T)
                    {
                        BoardInfoModel Model = new BoardInfoModel();
                        Model = Handle_Common.Mapper<BoardInfoModel, View_TransOnlineRecordsDetail>(Model, T);
                        Model.Index = ++i;
                        List_Model.Add(Model);
                    }
                }
                return List_Model;
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetTransOnLineInfo:" + ex.Message);
                return null;
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public ObservableCollection<BatchsModel> GetBatchsList()
        {
            ObservableCollection<BatchsModel> List_Model = new ObservableCollection<BatchsModel>();
            List<T_Nesting_BatchInfo> List_T = new List<T_Nesting_BatchInfo>();

            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    List_T = Db.T_Nesting_BatchInfo.ToList();

                    foreach (var T in List_T)
                    {
                        BatchsModel Model = Handle_Common.Mapper<BatchsModel, T_Nesting_BatchInfo>(new BatchsModel(), T);
                        List_Model.Add(Model);
                    }
                }
                return List_Model;
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetBatchsList:" + ex.Message);
                return null;
            }
        }

        public ObservableCollection<MprListModel> GetBorderListByBatch(string BatchId)
        {
            ObservableCollection<MprListModel> BatchesModel = new ObservableCollection<MprListModel>();
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    var data = Db.T_Nesting_BoardInfo.Where(s => s.BatchId == BatchId).ToList();

                    foreach (var item in data)
                    {
                        MprListModel model = new MprListModel
                        {
                            PartsAmount = item.PartsAmount,
                            MprName = item.MprName,
                            BoardInfoId = item.Id,
                            Details = new ObservableCollection<LabelTaskListModel>(),
                        };
                        BatchesModel.Add(model);
                    }
                }
                return BatchesModel;
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetBorderListByBatch:" + ex.Message);
                return null;
            }
        }

        public ObservableCollection<MprListModel> GetBorderDetailsListByBatch(ObservableCollection<MprListModel> mprList)
        {
            ObservableCollection<MprListModel> MprListModels = new ObservableCollection<MprListModel>();
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    foreach (var item in mprList)
                    {
                        int rate = 0;
                        var data = Db.View_LabelTaskDetail.Where(s => s.BoardInfoId == item.BoardInfoId).ToList();
                        foreach (var part in data)
                        {
                            if (part.Task_State == 6)
                            {
                                rate++;
                                item.CompletionRate = (int)rate * 100 / data.Count();
                            }
                        }
                        MprListModels.Add(item);
                    }
                }

                return MprListModels;
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetBorderDetailsListByBatch:" + ex.Message);
                return null;
            }
        }

        public ObservableCollection<LabelTaskListModel> GetMprDetailsByMprName(int Id)
        {
            ObservableCollection<LabelTaskListModel> partList = new ObservableCollection<LabelTaskListModel>();
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    var data = Db.View_LabelTaskDetail.Where(s => s.BoardInfoId == Id).ToList();
                    foreach (var part in data)
                    {
                        partList.Add(Handle_Common.Mapper<LabelTaskListModel, View_LabelTaskDetail>(new LabelTaskListModel(), part));
                    }
                }

                return partList;
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetMprDetailsByMprName:" + ex.Message);
                return null;
            }
        }

        public ObservableCollection<T_Nesting_LabelTask> GetPrintTasksList(string Reference = null)
        {
            ObservableCollection<T_Nesting_LabelTask> PaintModel = new ObservableCollection<T_Nesting_LabelTask>();
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    List<T_Nesting_LabelTask> data = null;

                    if (Reference == null || Reference == "")
                    {
                        data = Db.T_Nesting_LabelTask.OrderBy(item => item.State != 4).ThenBy(item => item.State != 6).ToList();
                    }
                    else
                    {
                        data = Db.T_Nesting_LabelTask.Where(s => s.Reference == Reference).OrderBy(item => item.State != 1).ThenBy(item => item.State != 0).ToList();
                    }

                    foreach (var item in data)
                    {
                        PaintModel.Add(item);
                    }
                }
                return PaintModel;
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetPrintTasksList:" + ex.Message);
                return null;
            }
        }

        public double GetTotalCompletionRate(string BatchId = "")
        {
            double TotalCompletionRate = 0;
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    if (BatchId != null && Db.View_LabelTaskDetail.Where(s => s.BatchId == BatchId).Count() <= 0)
                    {
                        return 0;
                    }
                    int c = Db.View_LabelTaskDetail.Where(s => s.Task_State == 6).Count();
                    int t = Db.View_LabelTaskDetail.Count();
                    if (t != 0) { TotalCompletionRate = (double)c / t * 100; }
                }
                return Math.Round(TotalCompletionRate, 2);
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetTotalCompletionRate:" + ex.Message);
                return 0;
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public View_TransOnlineRecordsDetail GetTransOnLineInfo(string Reference, string Position)
        {
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    return Db.View_TransOnlineRecordsDetail.
                        Where(s => s.Reference == Reference).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetTransOnLineInfo:" + ex.Message);
                return null;
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public bool GetS3P2HasPart()
        {
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    return Db.View_TransOnlineRecordsDetail.
                        Where(s => s.Location.Contains("4")).Count() > 0;
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetS3P2HasPart:" + ex.Message);
                return false;
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public View_TransOnlineRecordsDetail GetTransOnLineInfoByLocation(string Location = "10")
        {
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    return Db.View_TransOnlineRecordsDetail.
                        Where(s => s.Location == Location).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetTransOnLineInfoByLocation:" + ex.Message);
                return null;
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public View_LabelTaskDetail GetLabelTaskDetail(int State)
        {
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    return Db.View_LabelTaskDetail.FirstOrDefault(s => s.Task_State == State);
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetLabelTaskDetail:" + ex.Message);
                return null;
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public T_Nesting_BoardInfo GetLatestLabelTaskDetail_Board()
        {
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    return Db.T_Nesting_BoardInfo.Where(s => s.State != (int)EnumOfBoardOrBatchState.等待执行)
                                                    .OrderByDescending(s => s.Id).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetLatestLabelTaskDetail_Board:" + ex.Message);
                return null;
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public View_LabelTaskDetail GetLabelTaskForRePrint()
        {
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    return Db.View_LabelTaskDetail.Where(s => s.Task_State != 0).OrderByDescending(s => s.Id).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetLabelTaskForRePrint:" + ex.Message);
                return null;
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public ObservableCollection<SetttingsModel> GetSettingsInfo()
        {
            int i = 0;
            ObservableCollection<SetttingsModel> List_Model = new ObservableCollection<SetttingsModel>();
            List<T_SettingsConfig> List_T = new List<T_SettingsConfig>();
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    List_T = Db.T_SettingsConfig.ToList();
                    foreach (var T in List_T)
                    {
                        SetttingsModel Model = new SetttingsModel();
                        Model = Handle_Common.Mapper<SetttingsModel, T_SettingsConfig>(Model, T);
                        Model.Index = ++i;
                        List_Model.Add(Model);
                    }
                    return List_Model;
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetSettingsInfo:" + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 根据Ip查询设置
        /// </summary>
        /// <param name="Ip"></param>
        /// <returns></returns>
        public ObservableCollection<SetttingsModel> GetSettingsInfoById(String Ip)
        {
            int i = 0;
            ObservableCollection<SetttingsModel> List_Model = new ObservableCollection<SetttingsModel>();
            List<T_SettingsConfig> List_T = new List<T_SettingsConfig>();
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    List_T = Db.T_SettingsConfig.Where(s => s.Ip == Ip).ToList();
                    foreach (var T in List_T)
                    {
                        SetttingsModel Model = new SetttingsModel();
                        Model = Handle_Common.Mapper<SetttingsModel, T_SettingsConfig>(Model, T);
                        Model.Index = i;
                        List_Model.Add(Model);
                    }
                    return List_Model;
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetSettingsInfoById:" + ex.Message);
                return null;
            }
        }

        //获取系统版本数据
        public InformationModel GetSystemInfoMation()
        {
            InformationModel InforMationModel = new InformationModel();
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    InformationModel model = new InformationModel();
                    T_InformationConfig modelConfig = Db.T_InformationConfig.OrderByDescending(s => s.Id).FirstOrDefault();
                    return Handle_Common.Mapper<InformationModel, T_InformationConfig>(model, modelConfig); ;
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetSystemInfoMation:" + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 获取报错信息
        /// Error or Warning
        ///
        /// </summary>
        /// <param name="Type">Error or Warning </param>
        /// <returns></returns>
        public ObservableCollection<ErrorMessageModel> GetErrorMessageMation(string Type)
        {
            int i = 0;
            ObservableCollection<ErrorMessageModel> List_Model = new ObservableCollection<ErrorMessageModel>();
            List<T_ErrorMessage> List_T = new List<T_ErrorMessage>();
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    switch (Type)
                    {
                        case "All":
                            List_T = Db.T_ErrorMessage.ToList();
                            break;

                        case "Error":

                            List_T = Db.T_ErrorMessage.Where(s => s.State == 0).ToList();
                            break;

                        case "Warning":
                            List_T = Db.T_ErrorMessage.Where(s => s.State == 1).ToList();
                            break;

                        default:
                            break;
                    }

                    foreach (var T in List_T)
                    {
                        ErrorMessageModel Model = new ErrorMessageModel();
                        Model = Handle_Common.Mapper(Model, T);
                        Model.Index = ++i;
                        List_Model.Add(Model);
                    }
                    return List_Model;
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetErrorMessageMation:" + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 获取当前线上的板件数量
        ///
        /// </summary>
        /// <returns></returns>
        public bool GetActivatedPartsCount()
        {
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    return Db.View_TransOnlineRecordsDetail.Count() == 0;
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetActivatedPartsCount:" + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 获取总上线生产数量
        ///
        /// </summary>
        /// <returns></returns>

        public int GetTotalPartsCount()
        {
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    return Db.T_ScanRecords_Boards.Count();
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetTotalPartsCount:" + ex.Message);
                return 0;
            }
        }

        /// <summary>
        /// 获取历史信息
        /// Error or Warning
        ///
        public ObservableCollection<TransHistoryModel> GetTransHistoryMation(string Type, DateTime? ArrivalTime = null, DateTime? DepartureTime = null, string Reference = null)
        {
            int i = 0;
            ObservableCollection<TransHistoryModel> List_Model = new ObservableCollection<TransHistoryModel>();
            List<T_TransHistoryRecords> List_T = new List<T_TransHistoryRecords>();
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    IQueryable<T_TransHistoryRecords> query = Db.T_TransHistoryRecords;

                    if (Type != "All")
                    {
                        switch (Type)
                        {
                            case "OutFeed":
                                query = query.Where(s => s.Area.Equals("OutFeed"));
                                break;

                            case "InFeed":
                                query = query.Where(s => s.State.Equals("InFeed"));
                                break;

                            default:
                                break;
                        }
                    }

                    if (ArrivalTime.HasValue)
                    {
                        query = query.Where(s => s.ArrivalTime >= ArrivalTime.Value);
                    }
                    if (DepartureTime.HasValue)
                    {
                        query = query.Where(s => s.DepartureTime <= DepartureTime.Value);
                    }
                    if (!string.IsNullOrEmpty(Reference))
                    {
                        query = query.Where(s => s.Reference == Reference);
                    }

                    List_T = query.ToList();

                    foreach (var T in List_T)
                    {
                        TransHistoryModel Model = new TransHistoryModel();
                        Model = Handle_Common.Mapper(Model, T);
                        Model.Index = ++i;
                        List_Model.Add(Model);
                    }
                    return List_Model;
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetTransHistoryMation:" + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 获取Position信息
        ///
        /// </summary>
        /// <returns></returns>
        public ObservableCollection<string> GetLocationInfo(bool IsContainsM)
        {
            int i = 0;
            ObservableCollection<string> List_Model = new ObservableCollection<string>();
            List<T_LocationInfo> List_T = new List<T_LocationInfo>();
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    List_T = IsContainsM ? Db.T_LocationInfo.ToList()
                        : Db.T_LocationInfo.Where(s => !s.Section.Contains("M")).ToList();
                    foreach (var T in List_T)
                    {
                        List_Model.Add(T.Position);
                    }
                    return List_Model;
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetLocationInfo:" + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 获取Position信息
        ///
        /// </summary>
        /// <returns></returns>
        public List<T_LocationInfo> GetLocationDetailInfo(bool IsContainsM)
        {
            int i = 0;
            List<T_LocationInfo> List_T = new List<T_LocationInfo>();
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    List_T = IsContainsM ? Db.T_LocationInfo.ToList()
                        : Db.T_LocationInfo.Where(s => !s.Section.Contains("M")).ToList();

                    return List_T;
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetLocationDetailInfo:" + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 获取Mpr发送信息
        ///
        /// </summary>
        /// <returns></returns>
        public T_SendRecords_Mpr GetMprSendTimes(string Reference)
        {
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    return Db.T_SendRecords_Mpr.FirstOrDefault(s => s.Reference == Reference);
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetMprSendTimes:" + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// GetPnxInfo
        ///
        /// </summary>
        /// <returns></returns>
        public T_Nesting_PnxInfo GetPnxInfo(string BatchId, int PartId)
        {
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    return Db.T_Nesting_PnxInfo.Where(s => s.Run == BatchId && s.PartId == PartId).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetPnxInfo:" + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// GetPnxInfo
        ///
        /// </summary>
        /// <returns></returns>
        public string GetContextSettings()
        {
            try
            {
                using (Db_Printer Db = new Db_Printer())
                {
                    return Db.ContextSettings.Where(s => s.PrintContextName == "PartLabel").FirstOrDefault().PrintLayoutName;
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetContextSettings:" + ex.Message);
                return string.Empty;
            }
        }



        /// <summary>
        /// GetNestingBoardInfo
        ///
        /// </summary>
        /// <returns></returns>
        public T_Nesting_BoardInfo GetNestingBoardInfo(string MprName)
        {
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    return Db.T_Nesting_BoardInfo.FirstOrDefault(s => s.MprName.Equals(MprName));
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Search.Error("GetNestingBoardInfo:" + ex.Message);
                return null;
            }
        }
    }
}